package com.bs.auth.config;

import com.bs.auth.utils.Assert;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

import javax.annotation.Resource;

/**
 * @author bingshao
 * @date 2022/9/14
 **/
@Configuration
public class SmsAuthenticationProvider implements AuthenticationProvider {

    @Resource
    private UserDetailsService msgDetailsServiceImpl;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsAuthenticationToken authenticationToken = (SmsAuthenticationToken) authentication;
        String phone = (String) authenticationToken.getPrincipal();
        String code = (String) authenticationToken.getCredentials();
        // 模拟比对验证码
        if (!"123456".equals(code)) {
            Assert.isError("验证码错误");
        }

        UserDetails userDetails = msgDetailsServiceImpl.loadUserByUsername(phone);

        // 此处身份已经确认
        return createSuccessAuthentication(userDetails, authentication);
    }

    private Authentication createSuccessAuthentication(UserDetails userDetails, Authentication authentication) {
        SmsAuthenticationToken result = new SmsAuthenticationToken(userDetails, authentication.getCredentials(), userDetails.getAuthorities());
        result.setDetails(authentication.getDetails());
        return result;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return SmsAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
